package com.gitee.wsl.struct.generator.segment


import kotlinx.atomicfu.AtomicBoolean
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.sync.Mutex
import kotlin.concurrent.Volatile

/**
 * 特别声明: 此算法来自美团的leaf号段模式
 * see： https://github.com/Meituan-Dianping/Leaf/blob/master/leaf-server/src/main/java/com/sankuai/inf/leaf/server/service/SegmentService.java
 */
class SegmentBuffer(
        var key: Pair<String, String>? = null,
        ) {

    val segments: Array<Segment> = arrayOf(Segment(this), Segment(this)) //双buffer

    @Volatile
    var currentPos: Int = 0 //当前的使用的segment的index
        private set

    @Volatile
    var isNextReady: Boolean = false //下一个segment是否处于可切换状态

    @Volatile
    var isInitOk: Boolean = false //是否初始化完成

    val threadRunning: AtomicBoolean = atomic(false) //线程是否在运行中

    //private val lock: ReadWriteLock
    private val lock: Mutex = Mutex()

    @Volatile
    var step: Int = 0

    @Volatile
    var minStep: Int = 0

    @Volatile
    var updateTimestamp: Long = 0

    val current: Segment
        get() = segments[currentPos]

    fun nextPos(): Int {
        return (currentPos + 1) % 2
    }

    fun switchPos() {
        currentPos = nextPos()
    }

    fun rLock(): Mutex {
        //return lock.readLock()
        return lock
    }

    fun wLock(): Mutex {
        //return lock.writeLock()
        return lock
    }

    override fun toString(): String {
        val sb = StringBuilder("SegmentBuffer{")
        sb.append("key='").append(key).append('\'')
        sb.append(", segments=").append(segments.contentToString())
        sb.append(", currentPos=").append(currentPos)
        sb.append(", nextReady=").append(isNextReady)
        sb.append(", initOk=").append(isInitOk)
        sb.append(", threadRunning=").append(threadRunning)
        sb.append(", step=").append(step)
        sb.append(", minStep=").append(minStep)
        sb.append(", updateTimestamp=").append(updateTimestamp)
        sb.append('}')
        return sb.toString()
    }
}
